<template>
  <div class="app-container">
    <h3>新增付款单</h3>
    <hr/>

<!--    新增付款单表单-->
    <el-col :span="16" class="col">
      <el-form ref="form" :model="paymentPlanForm" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="收房合同号" prop="payOrderNo" label-width="100px">
              <el-input disabled v-model="paymentPlanForm.contractNo"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="getHouseContractList">收房合同查询</el-button>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房产信息" prop="payOrderNo">
              <el-input disabled v-model="paymentPlanForm.houseName"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row  type="flex">
          <el-col :span="8">
            <el-form-item label="业主姓名" prop="payOrderNo" label-width="100px">
              <el-input disabled v-model="paymentPlanForm.ownerName"/>
            </el-form-item>
          </el-col>
          <el-col :span="6"></el-col>
          <el-col :span="8">
            <el-form-item size="10" label="业主手机号" prop="payOrderNo" label-width="100px">
              <el-input disabled v-model="paymentPlanForm.ownerMobile"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row  type="flex">
          <el-col :span="20">
            <el-form-item label="选择账期" prop="payNumber" label-width="100px">
              <el-select v-model="paymentPlanForm.payNumber" placeholder="请选择" @change="onPayNumber">
                <el-option :label="'第'+item.payNumber+'期  '+item.paymentDaysBegin+'至'+item.paymentDaysEnd" :value="item.payNumber"  v-for="item in paymentDayVOList"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row  type="flex">
          <el-col :span="6">
            <el-form-item size="10" label="新增款项" prop="payOrderNo" label-width="100px">
              <el-button type="primary" @click="addItemType">点击添加</el-button>
            </el-form-item>
          </el-col>
        </el-row><br/>

        <el-form :inline="true" v-for="(item,index) in itemTypeList">
          <el-form-item label="费用类型">
            <el-select v-model="item.itemType" placeholder="请选择">
              <el-option v-for="dict in itemTypes" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应付金额">
            <el-input v-model="item.paymentAmount" placeholder="请输入应付金额"></el-input>
          </el-form-item>
          <el-form-item label="实付金额">
            <el-input v-model="item.realPaymentAmount" placeholder="请输入实付金额"></el-input>
          </el-form-item>
        </el-form>

        <br/><br/><br/><br/>

        <el-row  type="flex">
          <el-col :span="8">
            <el-form-item label="是否付款" prop="businessId">
              <el-radio v-model="paymentPlanForm.payState" label="2">未付款</el-radio>
              <el-radio v-model="paymentPlanForm.payState" label="1">已付款</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="6"></el-col>
          <el-col :span="8">
            <el-form-item v-if="paymentPlanForm.payState==1" size="10" label="付款日期" label-width="100px">
              <el-date-picker clearable  style="width: 200px"
                              v-model="paymentPlanForm.paidTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择账期开始日">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row  type="flex">
          <el-col :span="8">
            <el-form-item v-if="paymentPlanForm.payState==1" label="支付方式">
              <el-select  v-model="paymentPlanForm.payMethod" >
                <el-option v-for="dict in payWayList" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6"></el-col>
          <el-col :span="8">
            <el-form-item v-if="paymentPlanForm.payState==1" size="10" label="支付流水号" label-width="100px">
              <el-input v-model="paymentPlanForm.payFlowNo" placeholder="请输入支付流水号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row  type="flex">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="paymentPlanForm.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form><br/>
      <div >
        <el-button type="primary" @click="savePaymentPlan">确 定</el-button>
        <el-button type="primary" @click="zhifu" v-hasPermi="['financial:product:add']">支付</el-button>
        <el-button @click="cancel">清 空</el-button>
      </div>
    </el-col>

<!--    售房合同列表对话框-->
    <el-dialog
      title="收房合同查询"
      :visible.sync="dialogVisible"
      width="40%">

      <el-table
        v-loading="loading"
        :data="houseContractList"
        style="width: 100%">
        <el-table-column
          prop="ownerName"
          label="业主姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="houseName"
          label="房产信息"
          width="180">
          <template slot-scope="scope">
            <span>{{scope.row.premiseName}}</span>
            <span>({{scope.row.houseName}})</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="conSignTime"
          label="签约日期">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="getHouseContractById(scope.row)">选中</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--      分页-->
      <pagination
        v-show="houseContractTotal>0"
        :total="houseContractTotal"
        :page.sync="queryHouseContractParams.pageNum"
        :limit.sync="queryHouseContractParams.pageSize"
        @pagination="getHouseContractList"
      />
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>

<!--    支付图标-->
    <el-dialog
      align="center"
      :visible.sync="dialogVisiblePay"
      width="20%">
      <el-image :src="payQr"></el-image><br>
      <img src="@/assets/payTestImg/ali_app.svg"><!-- 支付宝图标 --><span>请使用支付宝“扫一扫”扫码支付</span>
    </el-dialog>
  </div>
</template>

<script>
import { houseContractList,getHouseContractById, getPlan, delPlan, save, updatePlan,pay } from "@/api/financing/paymentPlan";
import ReconnectingWebSocket from "reconnectingwebsocket";

export default {
  name: "addPaymentPlan",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 【请填写功能名称】表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询收房合同参数
      queryHouseContractParams: {
        pageNum: 1,
        pageSize: 5,
      },
      // 表单参数
      paymentPlanForm: {
        //合同ID
        contractId:null,
        //合同编号
        contractNo:null,
        //业主ID
        ownerId:null,
        //业主姓名
        ownerName:null,
        //小区(使用楼盘名)
        premiseName:null,
        houseName:null,
        ownerMobile:null,
        //付款状态
        payState:2,
        //备注
        remark:null,
        //第几期
        payNumber:null,
        //账期开始日
        paymentDaysBegin:null,
        //账期截止日
        paymentDaysEnd:null,
        //预定付款日期
        payableDate:null,
        //款项，应付，实付
        itemTypeDTOList:[],
        //实际付款日期
        paidTime:null,
        //支付方式
        payMethod:null,
        //支付方式
        payFlowNo:null,
      },
      form2: {},
      // 表单校验
      rules: {
        payOrderNo: [
          { required: true, message: "付款单号不能为空", trigger: "blur" }
        ],
        businessId: [
          { required: true, message: "商户ID不能为空", trigger: "blur" }
        ],
        contractId: [
          { required: true, message: "合同ID不能为空", trigger: "blur" }
        ],
        contractType: [
          { required: true, message: "合同类型,1：收房合同，2：出房合同不能为空", trigger: "change" }
        ],
        delFlg: [
          { required: true, message: "删除标识,0:未删除，1：删除不能为空", trigger: "blur" }
        ],
        createUserid: [
          { required: true, message: "创建用户ID不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateUserid: [
          { required: true, message: "更新用户ID不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      },
      //售房合同集合
      houseContractList:[],
      //售房合同的总条数
      houseContractTotal:0,
      //售房合同列表的对话框
      dialogVisible:false,
      //选择账期集合
      paymentDayVOList:[],
      //付款类型集合(包括应付是否金额)
      itemTypeList:[
        {}
      ],
      //付款类型集合
      itemTypes:[],
      //付款类型集合
      payWayList:[],
      //支付图标对话框
      dialogVisiblePay:false,
      payQr:null,
      payForm: {
        wayCode: 'ALI_QR',
        amount: 100,
        currency: 'CNY',
        subject: '支付测试',
        body: '支付描述',
        notifyUrl: 'http://43.142.33.78:9218/api/anon/paytestNotify/payOrder',
        payDataType: 'codeImgUrl'
      },
    };
  },
  created() {
    // this.getHouseContractList();
    //费用类型
    this.getDicts("financing_item_type").then(response => {
      this.itemTypes = response.data;
    });
    //支付类型
    this.getDicts("financing_pay_way").then(response => {
      this.payWayList = response.data;
    });
  },
  methods: {
    /** 查询收房合同列表 */
    getHouseContractList() {
      this.loading = true;
      this.dialogVisible = true;
      houseContractList(this.queryHouseContractParams).then(response => {
        this.houseContractList = response.rows;
        this.houseContractTotal = response.total;
        this.loading = false;
      });
    },
    // 根据id查询收房合同 和 可选账期
    getHouseContractById(row) {
      getHouseContractById(row.id).then(response=>{
        this.paymentPlanForm.contractId=response.data.sfContract.id;
        this.paymentPlanForm.contractNo=response.data.sfContract.sfContractNo;
        this.paymentPlanForm.houseName=response.data.sfContract.houseName;
        this.paymentPlanForm.ownerId=response.data.sfContract.ownerId;
        this.paymentPlanForm.ownerName=response.data.sfContract.ownerName;
        this.paymentPlanForm.ownerMobile=response.data.sfContract.ownerMobile;
        this.paymentPlanForm.premiseName=response.data.sfContract.premiseName;
        this.paymentDayVOList=response.data.paymentDayVOList;
        this.dialogVisible=false;
      })
    },
    //添加一行应付款项
    addItemType() {
      this.itemTypeList.push({});
    },
    //添加付款计划
    savePaymentPlan() {
      this.paymentPlanForm.itemTypeDTOList=this.itemTypeList;
      console.log("数据",this.paymentPlanForm);
      save(this.paymentPlanForm).then(response=>{
        if (response.data) {
          this.$message.success("添加成功");
          this.cancel();
          this.itemTypeList=[{}];
        }else {
          this.$message.error("添加失败");
        }
      })
    },
    //添加账期信息
    onPayNumber(val) {
      // console.log(val);
      this.paymentDayVOList.forEach(paymentDayVO=>{
        if (paymentDayVO.payNumber == val) {
          this.paymentPlanForm.paymentDaysBegin=paymentDayVO.paymentDaysBegin;
          this.paymentPlanForm.paymentDaysEnd=paymentDayVO.paymentDaysEnd;
          this.paymentPlanForm.payableDate=paymentDayVO.paymentDaysBegin;
        }
      })
    },
    // 取消按钮
    cancel() {
      this.paymentPlanForm={};
    },

    zhifu() {
      this.dialogVisiblePay = true;
      pay(this.payForm).then(response => {
        console.log(response);
        this.payQr = response.data.data.payData;
        // 监听响应结果
        this.payOrderWebSocket = new ReconnectingWebSocket('ws://43.142.33.78:9218/api/anon/ws/payOrder/' + response.data.data.payOrderId + '/' + new Date().getTime())
        this.payOrderWebSocket.onopen = () => {
        }
        this.payOrderWebSocket.onmessage = (msgObject) => {
          const resMsgObject = JSON.parse(msgObject.data)
          if (resMsgObject.state === 2) {
            this.dialogVisiblePay = false;
            this.$message.success("支付成功")
          } else {
            this.dialogVisiblePay = false;
            this.$message.error("支付失败")
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        payOrderNo: null,
        businessId: null,
        contractId: null,
        contractNo: null,
        contractType: null,
        tTerminationId: null,
        premiseId: null,
        premiseName: null,
        ownerId: null,
        ownerName: null,
        tenantId: null,
        tenantName: null,
        payType: null,
        payState: null,
        billType: null,
        itemType: null,
        otherItemName: null,
        paymentAmount: null,
        realPaymentAmount: null,
        withPayPlanId: null,
        paymentDaysBegin: null,
        paymentDaysEnd: null,
        payableDate: null,
        paidTime: null,
        payNumber: null,
        payMethod: null,
        otherPayMethod: null,
        payFlowNo: null,
        rentalPrice: null,
        tax: null,
        operationUser: null,
        totalPayNumber: null,
        repayType: null,
        remark: null,
        reserve1: null,
        reserve2: null,
        reserve3: null,
        reserve4: null,
        reserve5: null,
        delFlg: null,
        createUserid: null,
        createTime: null,
        updateUserid: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPlan(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/plan/export', {
        ...this.queryParams
      }, `system_plan.xlsx`)
    }
  }
};
</script>
<style scoped>
  .col{
    margin-left: 10%;
  }
</style>
